/*
 * @(#)CookieUtil.java
 *
 * Copyright 2012 by ShenY BIS, All rights reserved.
 */

package com.bis.framework.util.common;

import javax.servlet.http.Cookie;

/**
 * CookieUtil
 * 
 * @author BIS 2012-12-24
 */
public class CookieUtil
{

    /**
     * getCookie
     * @Description:
     * @param request
     * @param name
     * @return
     */
    public static Cookie getCookie(javax.servlet.http.HttpServletRequest request, String name)
    {
        try
        {
            Cookie cookies[] = request.getCookies();
            if (cookies == null || name == null || name.length() == 0)
            {
                return null;
            }
            for (int i = 0; i < cookies.length; i++)
            {
                if (name.equals(cookies[i].getName()))
                {
                    return cookies[i];
                }
            }
            return null;
        }
        catch (Exception ex)
        {
            return null;
        }
    }

    /**
     * deleteCookie
     * @Description:
     * @param request
     * @param response
     * @param cookie
     */
    public static void deleteCookie(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response, Cookie cookie)
    {
        if (cookie != null)
        {
            cookie.setPath(getPath(request));
            cookie.setValue("");
            cookie.setMaxAge(0);
            response.addCookie(cookie);
        }
    }

    /**
     * setCookie
     * @Description:
     * @param request
     * @param response
     * @param name
     * @param value
     */
    public static void setCookie(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response, String name, String value)
    {
        setCookie(request, response, name, value, 0x278d00);
    }

    /**
     * setCookie
     * @Description:
     * @param request
     * @param response
     * @param name
     * @param value
     * @param maxAge
     */
    public static void setCookie(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response, String name, String value, int maxAge)
    {
        Cookie cookie = new Cookie(name, value == null ? "" : value);
        cookie.setMaxAge(maxAge);
        cookie.setPath(getPath(request));
        response.addCookie(cookie);
    }

    /**
     * getPath
     * @Description:
     * @param request
     * @return
     */
    public static String getPath(javax.servlet.http.HttpServletRequest request)
    {
        String path = request.getContextPath();
        return (path == null || path.length() == 0) ? "/" : path;
    }

}
